import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue')
      },
      {
        path: 'thesis-topics',
        name: 'ThesisTopics',
        component: () => import('../views/thesis/TopicList.vue')
      },
      {
        path: 'topic-selections',
        name: 'TopicSelections',
        component: () => import('../views/thesis/SelectionList.vue')
      },
      {
        path: 'task-books',
        name: 'TaskBooks',
        component: () => import('../views/thesis/TaskBookList.vue')
      },
      {
        path: 'proposal-reports',
        name: 'ProposalReports',
        component: () => import('../views/thesis/ProposalReportList.vue')
      },
      {
        path: 'proposal-defenses',
        name: 'ProposalDefenses',
        component: () => import('../views/thesis/ProposalDefenseList.vue')
      },
      {
        path: 'guidance-records',
        name: 'GuidanceRecords',
        component: () => import('../views/thesis/GuidanceRecordList.vue')
      },
      {
        path: 'thesis-documents',
        name: 'ThesisDocuments',
        component: () => import('../views/thesis/DocumentList.vue')
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/system/UserList.vue'),
        meta: { requiresAdmin: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const user = JSON.parse(localStorage.getItem('user') || '{}')

  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.requiresAdmin && user.role !== 'admin') {
    next('/')
  } else {
    next()
  }
})

export default router 